<template>
  <div>
    <template v-if="readonly">
      <template v-if="tag2component[eleItem.argType] === 'file'">
        <div style="color: #409eff; cursor: pointer" @click="handleDownload">
          {{ (eleItem.argData || "").split(",")[1] || "" }}
        </div>
      </template>
      <template
        v-else-if="
          eleItem.argData && tag2component[eleItem.argType] === 'photo'
        "
      >
        <img
          style="width: 100%; height: 100%"
          :src="filePath + eleItem.argData.split(',')[0]"
        />
      </template>
      <template
        v-else-if="
          eleItem.argData && tag2component[eleItem.argType] === 'cascader'
        "
      >
        {{ eleItem.argData.join("/") }}
      </template>
      <template
        v-else-if="eleItem.dateDetail && eleItem.dateDetail.dateType === 2"
      >
        {{ eleItem.argData.join("至") }}
      </template>
      <template v-else>
        {{ eleItem.labelData }}
      </template>
    </template>
    <template v-else>
      <!-- 单行文本 -->
      <template v-if="tag2component[eleItem.argType] === 'input'">
        <el-input
          v-model="eleItem.argData"
          :placeholder="eleItem.textDetail.argPlaceholder"
          :maxlength="eleItem.textDetail.maxLength"
          :minlength="eleItem.textDetail.minLength"
          show-word-limit
        ></el-input>
      </template>
      <!-- 多行文本 -->
      <template v-if="tag2component[eleItem.argType] === 'textarea'">
        <el-input
          type="textarea"
          v-model="eleItem.argData"
          :placeholder="eleItem.textDetail.argPlaceholder"
          :maxlength="eleItem.textDetail.maxLength"
          :minlength="eleItem.textDetail.minLength"
          :rows="2"
          show-word-limit
        >
        </el-input>
      </template>
      <!-- 单选 -->
      <template v-if="tag2component[eleItem.argType] === 'radio'">
        <el-radio-group v-model="eleItem.argData">
          <el-radio
            v-for="(item, index) in eleItem.checkDetail"
            :key="item.index"
            :label="item.optionName"
            >{{ item.optionName }}</el-radio
          >
        </el-radio-group>
      </template>
      <!-- 多选 -->
      <template v-if="tag2component[eleItem.argType] === 'checkbox'">
        <el-checkbox-group v-model="eleItem.argData">
          <el-checkbox
            v-for="(item, index) in eleItem.checkDetail"
            :key="item.index"
            :label="item.optionName"
            >{{ item.optionName }}</el-checkbox
          >
        </el-checkbox-group>
      </template>
      <!-- 下拉框 -->
      <template v-if="tag2component[eleItem.argType] === 'select'">
        <el-select v-model="eleItem.argData" placeholder="请选择">
          <el-option
            v-for="item in eleItem.checkDetail"
            :key="item.optionName"
            :label="item.optionName"
            :value="item.optionName"
          >
          </el-option>
        </el-select>
      </template>
      <!-- 级联选择 -->
      <template v-if="tag2component[eleItem.argType] === 'cascader'">
        <el-cascader
          v-model="eleItem.argData"
          :options="eleItem.checkDetail"
          placeholder="请选择"
          :props="cascaderProps"
        ></el-cascader>
      </template>
      <!-- 日期选择器 -->
      <template v-if="tag2component[eleItem.argType] === 'datePicker'">
        <el-date-picker
          v-model="eleItem.argData"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :value-format="datePicker.valueFormat"
          :type="datePicker.type"
          :clearable="true"
        >
        </el-date-picker>
      </template>
      <template v-if="tag2component[eleItem.argType] === 'photo'">
        <CImgUpload
          :path="eleItem.argData?.split(',')[0]"
          :actionUrl="actionUrl"
          @uploadSuccess="handleSuccess"
          :beforeUpload="beforeFileUpload"
          @remove="handleRemove"
        >
          <template #tip>
            支持的格式包括:<br />
            图片：{{
              (acceptFileMap["psuffix"] || "").replace(
                new RegExp(",", "g"),
                "、"
              ) || "暂无"
            }}
          </template>
        </CImgUpload>
      </template>
      <!-- 文件 -->
      <template v-if="tag2component[eleItem.argType] === 'file'">
        <CFileUpload
          :path="eleItem.argData?.split(',')[0]"
          :actionUrl="actionUrl"
          :fileName="eleItem.argData?.split(',')[1]"
          @uploadSuccess="handleSuccess"
          :beforeUpload="beforeFileUpload"
          @remove="handleRemove"
        >
          <template #tip>
            支持的格式包括:<br />
            1、图片：{{
              (acceptFileMap["psuffix"] || "").replace(
                new RegExp(",", "g"),
                "、"
              ) || "暂无"
            }}; 2、视频：{{
              (acceptFileMap["vsuffix"] || "").replace(
                new RegExp(",", "g"),
                "、"
              ) || "暂无"
            }}
            3、音频：{{
              (acceptFileMap["asuffix"] || "").replace(
                new RegExp(",", "g"),
                "、"
              ) || "暂无"
            }}

            4、文档：{{
              (acceptFileMap["dsuffix"] || "").replace(
                new RegExp(",", "g"),
                "、"
              ) || "暂无"
            }}
          </template>
        </CFileUpload>
      </template>
    </template>
  </div>
</template>
<script>
import { basePath } from "@/utils/request";
import { getToken } from "@/utils/auth";
import {
  tag2component,
  dateMap,
  isArray,
} from "@/views/system-config/form-generate/config.js";
import Download from "@/views/_mixins/download";
import CFileUpload from "@/components/Upload/CFileUpload";
import CImgUpload from "@/components/Upload/CImgUpload";
export default {
  name: "FormItemGenerator",
  props: ["eleItem", "eleConfig", "readonly"],
  mixins: [Download],
  data() {
    return {
      filePath,
      loading: false,
      tag2component,
      actionUrl: basePath + "media/file",
      datePicker: {
        valueFormat: "",
        type: "",
      },
      cascaderProps: {
        value: "optionName",
        label: "optionName",
        children: "subOption",
        // emitPath: false,
      },
    };
  },
  components: {
    CFileUpload,
    CImgUpload,
  },
  computed: {
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
    acceptFileMap() {
      const type = tag2component[this.eleItem.argType];
      let map = [];
      if (type === "photo") {
        map = ["psuffix"];
      } else if (type === "file") {
        map = ["psuffix", "asuffix", "dsuffix", "vsuffix"];
      } else {
        return {};
      }
      let result = {};
      for (const item of map) {
        result[item] = this.eleItem.fileDetail[item];
      }
      return result;
    },
  },
  created() {
    this.initDate();
    this.initArray();
    this.initCascader();
  },
  methods: {
    initCascader(arr = this.eleItem.checkDetail) {
      if (!arr) return;
      for (const item of arr) {
        if (!item.subOption || !item.subOption.length) {
          item.subOption = undefined;
        } else {
          this.initCascader(item.subOption);
        }
      }
    },
    initArray() {
      if (isArray.includes(tag2component[this.eleItem.argType])) {
        if (!this.eleItem.argData) {
          this.$set(this.eleItem, "argData", []);
        }
      }
    },
    initDate() {
      if (tag2component[this.eleItem.argType] !== "datePicker") {
        return;
      }
      for (const key in dateMap) {
        if (Object.hasOwnProperty.call(dateMap, key)) {
          const { dateLength, dateType, format } = dateMap[key];
          if (
            this.eleItem.dateDetail.dateLength === dateLength &&
            this.eleItem.dateDetail.dateType === dateType
          ) {
            this.datePicker = {
              valueFormat: format,
              type: key,
            };
          }
        }
      }
    },
    // 文件上传前的校验 —— 常见的校验有：校验文件类型，文件大小
    beforeFileUpload(file) {
      if (!file) {
        return;
      }
      // 允许上传的文件格式列表
      let acceptList = [];
      for (const key in this.acceptFileMap) {
        if (Object.hasOwnProperty.call(this.acceptFileMap, key)) {
          const element = this.acceptFileMap[key];
          acceptList = acceptList.concat(element.split(","));
        }
      }
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split(".").pop().toLowerCase();
      // 判断文件格式是否符合要求
      if (acceptList.indexOf(fileType) === -1) {
        this.$message.error(
          "请按照提示上传文件，不能上传 " + fileType + " 格式!"
        );
        this.loading = false;
        return false;
      }
    },
    handleSuccess(res, file, fileList) {
      if (!!res.code) {
        this.handleError(res);
      } else {
        this.$set(
          this.eleItem,
          "argData",
          `${res.fileUrl},${res.name.replace(new RegExp(",", "g"), "")},${
            res.id
          }`
        );
      }
    },
    handleRemove() {
      this.eleItem.argData = "";
    },
    handleOnChange(file, fileList) {
      this.loading = true;
      if (file.percentage == 100) {
        this.loading = false;
      }
    },
    handleError(err, file, fileList) {
      this.$message.closeAll();
      this.$message.error("文件上传失败，请重试");
      this.$emit("upload-error", err);
    },
    handleDownload() {
      let that = this;
      that.$message("正在下载中...");
      let inter = setInterval(() => {
        that.$message("正在下载中...");
      }, 4000);
      const data = (this.eleItem.argData || "").split(",");
      this.downloadFile(data[0] + "?type=download", data[1], inter);
    },
  },
};
</script>
<style scoped>
.radioLineHeight {
  line-height: 32px;
}
.form-text {
  margin-left: -100px;
  font-style: unset;
}
</style>
